package com.lilicould.controller;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.lilicould.entity.Grades;
import com.lilicould.service.GradeService;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.List;

@WebServlet("/grade/*")
public class GradeController extends BaseServlet {

    // 根据学号查询成绩
    public void list(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("json/application;charset=utf-8");
        String userNo = req.getParameter("userNo");
        String result = new GradeService().getGradesByUserNo(userNo);
        if (result != null) {
            // 成功获取到成绩信息
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.getWriter().write(result);
        } else {
            // 未获取到成绩信息
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    // 根据课程安排ID查询成绩
    public void listByScheduleId(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("json/application;charset=utf-8");
        String scheduleId = req.getParameter("scheduleId");
        String result = new GradeService().getGradesByScheduleId((Integer.parseInt(scheduleId)));
        if (result != null) {
            // 获取成功
            resp.setStatus(HttpServletResponse.SC_OK);
            resp.getWriter().write(result);
        } else {
            // 获取失败
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }

    // 录入成绩
    public void addGrades(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        resp.setContentType("json/application;charset=utf-8");

        // 获取请求体中的数据
        List<Grades> grades = new Gson().fromJson(req.getReader(), new TypeToken<List<Grades>>() {}.getType());
        String result = new GradeService().addGrades(grades);
        if (result != null) {
            // 有错误信息返回，返回400状态码和错误信息
            resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
            resp.getWriter().write(result);
        } else {
            // 录入成功
            resp.setStatus(HttpServletResponse.SC_OK);
        }
    }
}
